const fs = require('fs');
const path = require('path');

const html_path = '/Users/zhangxiangyu/Documents/lesson1/second/clock.html'
const Generator = path.join('second','new_clock.html')
// console.log(path.dirname(html_path))

fs.readFile(html_path, 'utf8', (err, htmlContent) => {
    if(err){
        console.error('读取HTML文件失败:', err.message);
        return;
    }
    file_content = htmlContent;
    CSS = split_CSS(file_content)
    // console.log(CSS)
    JS = split_JS(file_content)
    // console.log(JS)

    fs.writeFile(path.join('second','extracted_css.css'), CSS.embeddedCSS.join('\n'), (err) => {
        if (err) throw err;
        console.log('CSS已保存到文件');
    });

    fs.writeFile(path.join('second','extracted_js.js'), JS.embeddedJS.join('\n'), (err) => {
        if (err) throw err;
        console.log('JS已保存到文件');
    });

    const newHtmlContent = htmlContent.replace(
        /<style[^>]*>([\s\S]*?)<\/style>/gi,
        `<link rel="stylesheet" href="${path.basename('extracted_css.css')}">`
    ).replace(
        /<script[^>]*>([\s\S]*?)<\/script>/gi,
        `<script src="${path.basename('extracted_js.js')}"></script>`
    );
    fs.writeFile(Generator, newHtmlContent, (err) => {
        if (err) throw err;
        console.log('HTML已保存到文件');
    });
})

function split_CSS(htmlContent) { 
    let res = {
        embeddedCSS: [],   
    };
    const styleRegex = /<style[^>]*>([\s\S]*?)<\/style>/gi;
    let match;
    while ((match = styleRegex.exec(htmlContent)) !== null) {
        res.embeddedCSS.push(match[1]);
    }
    return res;
}


function split_JS(htmlContent) { 
    let res = {
        embeddedJS: [],   
    };
    const styleRegex = /<script[^>]*>([\s\S]*?)<\/script>/gi;
    let match;
    while ((match = styleRegex.exec(htmlContent)) !== null) {
        res.embeddedJS.push(match[1]);
    }
    return res;
}